package cn.gov.pbc.gd.credit.provider.api.log.impl;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.mapreduce.GroupBy;
import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.liu.jbase.PageListVo;
import com.liu.jbase.service.mongo.IMongoClient;
import com.liu.tools.DateUtil;
import com.liu.tools.LogUtil;
import com.liu.tools.StrUtil;
import com.mongodb.BasicDBList;

import cn.gov.pbc.gd.credit.api.log.ILogInquiryApi;
import cn.gov.pbc.gd.credit.vo.log.LogInquiryVo;

@Service
public class LogInquiryApiImpl implements ILogInquiryApi{
	
	private static Logger logger = LoggerFactory.getLogger(LogInquiryApiImpl.class);
	
	@Autowired
	private IMongoClient<LogInquiryVo> mongoClient;

	@Override
	public void insert(LogInquiryVo entity) throws Exception {
		mongoClient.insert(entity);		
	}

	@Override
	public void updateById(Serializable id, String key, String value) throws Exception {
		
		mongoClient.updateById(id, key, value, LogInquiryVo.class);		
	}

	@Override
	public void update(LogInquiryVo vo) throws Exception {
		
		Query query = new Query();
		query.addCriteria(Criteria.where("inquiryId").is(vo.getInquiryId()));
		
		Update update = new Update().set("updateTime", Calendar.getInstance().getTime());
		if(StrUtil.isNotNull(vo.getQueryResult())){
			update.set("queryResult", vo.getQueryResult());
		}
		
		if(StrUtil.isNotNull(vo.getReportCode())){
			update.set("reportCode", vo.getReportCode());
		}
		
		mongoClient.update(query, update, LogInquiryVo.class);		
	}

	@Override
	public void update(LogInquiryVo vo, String key, String value) throws Exception {
		
		Query query = new Query();
		
		mongoClient.update(query, key, value, LogInquiryVo.class);
		
	}

	@Override
	public void deleteById(Serializable id) throws Exception {
		mongoClient.deleteById(id, LogInquiryVo.class);
		
	}

	@Override
	public void deleteByQuery(LogInquiryVo vo) throws Exception {
		
		Query query = new Query();
		
		mongoClient.deleteByQuery(query, LogInquiryVo.class);
		
	}

	@Override
	public LogInquiryVo getOneById(Serializable id) throws Exception {

		return mongoClient.getOneById(id, LogInquiryVo.class);
	}

	@Override
	public LogInquiryVo getOne(LogInquiryVo vo) throws Exception {
		
		Query query = new Query();
		
		return mongoClient.getOne(query, LogInquiryVo.class);
	}

	@Override
	public List<LogInquiryVo> getAll(Class<LogInquiryVo> entity) throws Exception {
		return mongoClient.getAll(entity);
	}

	@Override
	public List<LogInquiryVo> getAll(LogInquiryVo vo) throws Exception {

		Query query = new Query();

		
		if (StrUtil.isNotNull(vo.getAccount())) {// 1.账号

			Pattern pattern = Pattern.compile("^.*" + vo.getAccount() + ".*$", Pattern.CASE_INSENSITIVE);

			query.addCriteria(Criteria.where("account").regex(pattern));
		}
		
		if(StrUtil.isNotNull(vo.getQueryResult())){
			query.addCriteria(Criteria.where("queryResult").is(vo.getQueryResult()));
		}
		
		if (StrUtil.isNotNull(vo.getCardNum())) { // 2.身份证号

			Pattern pattern = Pattern.compile("^.*" + vo.getCardNum() + ".*$", Pattern.CASE_INSENSITIVE);

			query.addCriteria(Criteria.where("cardNum").regex(pattern));

		}

		if (vo.getBeginTime() != null && vo.getEndTime() != null) {// 3.开始时间和结束时间

			query.addCriteria(Criteria.where("createTime").gte(vo.getBeginTime()).lte(vo.getEndTime()));
		}
		if (vo.getBeginTime() != null && vo.getEndTime() == null) {// 3.开始时间
			query.addCriteria(Criteria.where("createTime").gte(vo.getBeginTime()));
		}

		if (vo.getEndTime() != null && vo.getBeginTime() == null) {// 4.结束时间，lte小于等于

			query.addCriteria(Criteria.where("createTime").lte(vo.getEndTime()));
		}

		if (vo.getUserName() != null && vo.getUserName() != "" && vo.getUserName().length() > 0) {//被查人姓名

			Pattern pattern = Pattern.compile("^.*" + vo.getUserName() + ".*$", Pattern.CASE_INSENSITIVE);

			query.addCriteria(Criteria.where("userName").regex(pattern));
		}
		
		query.with(new Sort(new Order(Direction.DESC,"createTime")));  
		
		return mongoClient.getAll(query, LogInquiryVo.class);
	}

	@Override
	public long getCount(LogInquiryVo vo) throws Exception {
		
		Query query = new Query();
		
//		 String reduce = "function(doc, aggr){" +
//	                "            aggr.count += 1;" +
//	                "        }";
//	        Query query = Query.query(Criteria.where("age").exists(true));
//	        DBObject result = mongoTemplate.getCollection("person").group(new BasicDBObject("age", 1), 
//	                query.getQueryObject(), 
//	                new BasicDBObject("count", 0),
//	                reduce);
//	        
//	        Map map = result.toMap();
//	        System.out.println(map);
//	        for (Map.Entry o : map.entrySet()) {
//	            System.out.println(o.getKey() + "  " + o.getValue());
//	        }
		
		return mongoClient.getCount(query, LogInquiryVo.class);
	}

	@Override
	public PageListVo<LogInquiryVo> getPage(LogInquiryVo vo, PageListVo<LogInquiryVo> page) throws Exception {
		
		Query query = new Query();

//		if (vo.getLoginResult() != null && vo.getLoginResult() != 0) {// 1. 行为状态
//
//			query.addCriteria(Criteria.where("loginResult").is(vo.getLoginResult()));
//		}
		
		if (StrUtil.isNotNull(vo.getAccount())) {// 1.账号

			Pattern pattern = Pattern.compile("^.*" + vo.getAccount() + ".*$", Pattern.CASE_INSENSITIVE);

			query.addCriteria(Criteria.where("account").regex(pattern));
		}
		
		if(StrUtil.isNotNull(vo.getQueryResult())){
			query.addCriteria(Criteria.where("queryResult").is(vo.getQueryResult()));
		}
		
		if (StrUtil.isNotNull(vo.getCardNum())) { // 2.身份证号

			Pattern pattern = Pattern.compile("^.*" + vo.getCardNum() + ".*$", Pattern.CASE_INSENSITIVE);

			query.addCriteria(Criteria.where("cardNum").regex(pattern));

		}

		if (vo.getBeginTime() != null && vo.getEndTime() != null) {// 3.开始时间和结束时间

			query.addCriteria(Criteria.where("createTime").gte(vo.getBeginTime()).lte(vo.getEndTime()));
		}
		if (vo.getBeginTime() != null && vo.getEndTime() == null) {// 3.开始时间
			query.addCriteria(Criteria.where("createTime").gte(vo.getBeginTime()));
		}

		if (vo.getEndTime() != null && vo.getBeginTime() == null) {// 4.结束时间，lte小于等于

			query.addCriteria(Criteria.where("createTime").lte(vo.getEndTime()));
		}

		if (vo.getUserName() != null && vo.getUserName() != "" && vo.getUserName().length() > 0) {//被查人姓名

			Pattern pattern = Pattern.compile("^.*" + vo.getUserName() + ".*$", Pattern.CASE_INSENSITIVE);

			query.addCriteria(Criteria.where("userName").regex(pattern));
		}
		
		query.with(new Sort(new Order(Direction.DESC,"createTime")));  
		
		return mongoClient.getPage(query, page, LogInquiryVo.class);
	}

	@Override
	public Map<String, Object> totalForPage(LogInquiryVo vo) throws Exception {
		
		Query query = new Query();
		
		String startTimeStr = DateUtil.format(new Date(), "yyyyMMdd") + "000000000";
		String endTimeStr = DateUtil.format(new Date(), "yyyyMMdd") + "235959999";
		long startTime = Long.parseLong(startTimeStr);
		long endTime = Long.parseLong(endTimeStr);
		query.addCriteria(Criteria.where("createMills").gte(startTime).lte(endTime));
		long curDayQueryTotal = mongoClient.getCount(query, LogInquiryVo.class);
		

//      //大于16以上的查询年龄总和是多少，和数量是是多少？
       GroupBy groupBy = GroupBy.key("cardNum").initialDocument("{count:0}") 
                        .reduceFunction("function(doc, prev){prev.count+=1;}");
//      .finalizeFunction("function(prev){prev.avg=prev.allAgeTotal/prev.count;}");
       Criteria criteria = new Criteria();
       criteria.and("createMills").gte(startTime).lte(endTime);
       GroupByResults<LogInquiryVo> r = mongoClient.group(criteria, "logInquiryVo", groupBy, LogInquiryVo.class);
       BasicDBList list = (BasicDBList)r.getRawResults().get("retval"); 
       long curDayQueryUser = list.size();
       logger.info(LogUtil.msg("LogInquiryApiImpl:totalForPage", "查询用户总量:" + curDayQueryUser));
//      for (int i = 0; i < list.size(); i ++) { 
//          BasicDBObject obj = (BasicDBObject)list.get(i); 
//          System.out.println("[LOG]数量=" + obj.get("count"));         
//      } 
       
       
        GroupBy groupBy1 = GroupBy.key("operatorId").initialDocument("{count:0}") 
               .reduceFunction("function(doc, prev){prev.count+=1;}");
		//.finalizeFunction("function(prev){prev.avg=prev.allAgeTotal/prev.count;}");

		 r = mongoClient.group(criteria, "logInquiryVo", groupBy1, LogInquiryVo.class);
		list = (BasicDBList)r.getRawResults().get("retval"); 
		long curDayOperateUser = list.size();
		logger.info(LogUtil.msg("LogInquiryApiImpl:totalForPage", "查询用户虚拟用户:" + curDayOperateUser));
	     
	    Map<String, Object> map = new HashMap<>();
	    map.put("curDayQueryTotal", curDayQueryTotal);
	    map.put("curDayQueryUser", curDayQueryUser);
	    map.put("curDayOperateUser", curDayOperateUser);
	     
		return map;
		
	}
	
	

}
